package com.ars.personalInfomation;

import com.ars.db.DBTools;
import com.ars.main.User;

import javax.swing.*;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UpdatePassword {

    //显示面板
    public void show() {
        String oldPassword = JOptionPane.showInputDialog("请输入旧的密码：");
        if (oldPassword == null) {
            return;
        } else if (oldPassword.equals(getOldPassword())) {
            String newPassword = JOptionPane.showInputDialog("请输入新的密码");
            updateDB(newPassword);
        } else {
            JOptionPane.showMessageDialog(null, "修改失败，密码错误！", "警告", JOptionPane.ERROR_MESSAGE);
        }
    }

    //获取用户名
    private String getUserName() {
        return User.getName();
    }

    //获取旧密码
    private String getOldPassword() {
        String sql = "SELECT password FROM website WHERE name = '" + getUserName() + "';";
        ResultSet rs = new DBTools().query(sql);
        try {
            if (rs.next()) {
                return rs.getString("password");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //更新数据库
    private void updateDB(String newPassword) {
        if (newPassword == null) {
            return;
        } else if (newPassword.equals("")) {
            JOptionPane.showMessageDialog(null, "密码不能为空！", "警告", JOptionPane.ERROR_MESSAGE);
        } else {
            String sql = "UPDATE website set password = '" + newPassword + "' WHERE name = '" + getUserName() + "'";
            new DBTools().update(sql);
            JOptionPane.showMessageDialog(null, "操作成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

}
